package com.example.vertification.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.vertification.Utils.RedisUtil;
import com.example.vertification.Utils.Utils;
import com.example.vertification.entity.User;
import com.example.vertification.service.RegisterCodeService;
import com.example.vertification.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@Api(value = "用户管理", tags = "用户管理API")
public class UserController {

    private final UserService userService;
    private final RegisterCodeService registerCodeService;

    @Value("${img-path}")
    private String imgPath;


    @Autowired
    public UserController(UserService userService,RegisterCodeService registerCodeService) {
        this.userService = userService;
        this.registerCodeService = registerCodeService;
    }

    @ApiOperation(value = "生成注册验证码，IP绑定的形式,返回五位code字母")
    @GetMapping("/generate_register_code")
    public ResponseEntity<?> generateRegisterCode(HttpServletRequest request) {
        String ipAddress = Utils.getIpByServerlet(request);
        System.out.println(ipAddress);
        // 生成新的验证码
        String code = Utils.generateCode();
        // 将验证码与IP绑定并存储
        registerCodeService.setCodeWithBoundIP(ipAddress, code);
        // 返回成功响应，包含验证码
        return new ResponseEntity<>(code, HttpStatus.OK);
    }



    @PostMapping("/UserCardFullfill")
    @ApiOperation(value = "首次注册完善资料，传入的参数依次为token,用户昵称，头像，身份")
    public ResponseEntity<?> UserCardFullfill(@RequestParam String username,
                                              @RequestParam String token,
                                              @RequestParam String position,@RequestParam String address,
                                              @RequestParam(value = "file", required = false) MultipartFile file,  HttpServletRequest request) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","登入失败,无法完善资料卡");
            return new ResponseEntity<>(obj,HttpStatus.OK);
        }
        long maxFileSizeInBytes = 5*1024 * 1024; // 5MB
        if (file == null) {
            // 处理file为null的情况，可能是返回一个错误响应或者抛出一个异常
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","文件对象为空");
            return new ResponseEntity<>(obj, HttpStatus.OK);
        }
        if (file.getSize() > maxFileSizeInBytes) {
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","文件大小超过限制，请上传小于5MB的图片");
            return new ResponseEntity<>(obj, HttpStatus.OK);
        }
        // 构建保存图片的目录路径
        String filePath = imgPath.replace("file:","");
        File filee=new File(filePath);
        if(!filee.exists()){
            filee.mkdirs();
        }
        //新文件的路径
        file.transferTo(new File(filePath + u.getUid() + ".jpg"));
        u.setName(username);
        u.setPosition(Integer.valueOf(position));
        u.setAddress(address);
        userService.saveUser(u);
        JSONObject obj = JSONUtil.createObj();
        obj.set("status","200");
        obj.set("result","完善成功");
        return  new ResponseEntity<>(obj,HttpStatus.OK);
    }


    @GetMapping("/register")
    @ApiOperation(value = "注册账号，传入的参数依次为 注册验证码，手机号,密码")
    public ResponseEntity<?> register( @RequestParam String code,
                           @RequestParam String telephone,
                           @RequestParam String password, HttpServletRequest request) {

        String ipAddress = Utils.getIpByServerlet(request);
        if(registerCodeService.getCodeByIP(ipAddress) == null){
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","该用户尚未生成验证码!");
            return new ResponseEntity<>(obj,HttpStatus.OK);
        }else if(!(registerCodeService.getCodeByIP(Utils.getIpByServerlet(request)).equalsIgnoreCase(code))){
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","验证码不匹配!");
            return new ResponseEntity<>(obj,HttpStatus.OK);
        }
        if(userService.getUserByTelephone(telephone) != null){
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","用户已被注册!");
            return new ResponseEntity<>(obj, HttpStatus.OK);
        }
        User user = new User();
        user.setTelephone(telephone);
        user.setPassword(password);
        user.setScore(0);
        user.setExp(0);
        user.setLevel(1);
        user.setAddress("");

        userService.createUser(user);
        userService.Login(user.getTelephone(),user.getPassword());
        JSONObject obj = JSONUtil.createObj();
        obj.set("status","200");
        obj.set("result","注册成功");
        obj.set("token",userService.getTokenByUID(String.valueOf(user.getUid())));
        return new ResponseEntity<>(obj, HttpStatus.OK);

    }



    @GetMapping("/login")
    @ApiOperation(value = "登入接口,传入账号,密码。返回登入口令", notes ="登入,传入账号,密码。返回登入口令")
    public ResponseEntity<?> login(@RequestParam String account, @RequestParam String password) {
        User u = userService.Login(account,userService.encryptPassword(password));
        if(u==null){
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","登入失败");
            return new ResponseEntity<>(obj,HttpStatus.OK);
        }else{
            String token = userService.getTokenByUID(String.valueOf(u.getUid()));
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","200");
            obj.set("result","登入成功");

            JSONObject user_obj = JSONUtil.parseObj(u);
            user_obj.set("password","*******");
            user_obj.set("token",token);
            obj.set("data",user_obj);

            return new ResponseEntity<>(obj,HttpStatus.OK);
        }
    }

    @GetMapping("/getUserByToken")
    @ApiOperation(value = "检测登入口令是否有效，返回用户一系列数据")
    public ResponseEntity<?> getUserByToken(@RequestParam(required = false) String token) {

        if(token==null){
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","未发送口令");
            return new ResponseEntity<>(obj,HttpStatus.OK);
        }

        User u = userService.getUserByToken(token);
        if(u==null){
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","口令已过期");
            return new ResponseEntity<>(obj,HttpStatus.OK);
        }else{
            JSONObject obj = JSONUtil.createObj();
            obj.set("status","201");
            obj.set("result","登入成功");
            JSONObject user_obj = JSONUtil.parseObj(u);
            user_obj.set("password","*******");
            user_obj.set("head_img","/img/"+u.getUid()+".jpg");
            obj.set("data",user_obj);

            return new ResponseEntity<>(obj,HttpStatus.OK);
        }
    }


    @GetMapping("/changepassword")
    @ApiOperation(value = "修改密码接口,传入账号或者手机号,老的密码,新的密码", notes ="修改密码,传入账号或者手机号,老的密码,新的密码")
    public ResponseEntity<?> changepassword(@RequestParam String token, @RequestParam String password,@RequestParam String new_password) {
        User u = userService.getUserByToken(token);
        if(u==null){
            return new ResponseEntity<>("修改失败" ,HttpStatus.OK);
        }else{

            if(!userService.encryptPassword(password).equals(u.getPassword())){
                return new ResponseEntity<>("当前密码错误" ,HttpStatus.OK);
            }

            u.setPassword(new_password);
            userService.saveUser(u);
            return new ResponseEntity<>("修改成功,"+u.getName() ,HttpStatus.OK);
        }
    }

    @GetMapping("/editname")
    @ApiOperation(value = "修改用户昵称,修改用户昵称,传入登入口令，新的名字", notes ="修改用户昵称,传入登入口令，新的名字")
    public ResponseEntity<?> editname(@RequestParam(required = false) String token,@RequestParam String new_name) {
        User u = userService.getUserByToken(token);
        if(u == null){
            return new ResponseEntity<>("未登入,请先登录在进行操作" ,HttpStatus.OK);
        }else{
            u.setName(new_name);
            userService.saveUser(u);
            return new ResponseEntity<>("修改成功" ,HttpStatus.OK);
        }
    }



    @GetMapping("/edittelephone")
    @ApiOperation(value = "修改用户手机号，传入登入口令，手机号", notes ="修改用户手机号,传入登入口令，手机号")
    public ResponseEntity<?> edittelephone(@RequestParam(required = false) String token,@RequestParam String now_password,@RequestParam String new_telephone) {
        User u = userService.getUserByToken(token);
        if(u == null){
            return new ResponseEntity<>("未登入,请先登录在进行操作" ,HttpStatus.OK);
        }else{

            if(!u.getPassword().equalsIgnoreCase(userService.encryptPassword(now_password))){
                return new ResponseEntity<>("当前密码不正确" ,HttpStatus.OK);
            }

            if(userService.getUserByTelephone(new_telephone)!=null){
                return new ResponseEntity<>("该手机号已被他人绑定" ,HttpStatus.OK);
            }

            u.setTelephone(new_telephone);
            userService.saveUser(u);
            return new ResponseEntity<>("修改成功" ,HttpStatus.OK);
        }
    }



    @PostMapping("/upload_headimg")
    @ApiOperation(value = "上传用户头像,传入登入口令token，头像文件", notes ="修改用户头像,传入登入口令，头像文件")
    public ResponseEntity<?> upload_headimg(@RequestParam(required = false) String token,MultipartFile file) throws IllegalStateException, IOException {
        User u = userService.getUserByToken(token);
        if(u == null) {
            return new ResponseEntity<>("未登入,请先登录在进行操作" ,HttpStatus.OK);
        }

        long maxFileSizeInBytes = 5*1024 * 1024; // 1MB
        if (file.getSize() > maxFileSizeInBytes) {
            return new ResponseEntity<>("文件大小超过限制，请上传小于5MB的图片" ,HttpStatus.OK);
        }
        // 构建保存图片的目录路径
        String filePath = imgPath.replace("file:","");
        File filee=new File(filePath);
        if(!filee.exists()){
            filee.mkdirs();
        }
        //新文件的路径
        file.transferTo(new File(filePath + u.getUid() + ".jpg"));
        userService.saveUser(u);
        return  new ResponseEntity<>("成功",HttpStatus.OK);
    }







    @GetMapping("/getUserByUID")
    @ApiOperation(value = "通过用户的UID，获取对应的数据[密码会隐藏,敏感数据无法查阅]")
    public ResponseEntity<?> getUserByUID(@RequestParam String uid) {
        User u = userService.getUserByUId(Long.valueOf(uid));
        if(u==null){
            return ResponseEntity.ok("该用户不存在");
        }
        u.setPassword("*****");
        return ResponseEntity.ok(u);
    }






}
